var redisModule = require("redis");
var myRedis = {
    redis:{},
    result:{},
    config:function(port,host){
        this.redisModule = redisModule;
        this.port = port;
        this.host = host;
        return this;
    },
    create:function(){
        this.redis = this.redisModule.createClient(this.port,this.host);
        //连接错误处理
        this.redis.on("error", function(error){
            console.error(error);
            throw error;
        });
        return this;
    },
    get:function(key){
        return new Promise(resolve => {
            switch (arguments.length){
                case 1:
                    this.redis.get(key,function(error,row){if(!error){resolve(row);}else{reject(error)}});
                    break;
                case 2:
                    this.redis.get(key,arguments[1]);
                    break;
            }
        });
    },
    del:function(key){
        return new Promise(resolve => {
            this.redis.del(key,function(error,row){if(!error){resolve(row);}else{reject=>{reject(error)}}});
        });
    },
    set:function(key,value){
        return new Promise(resolve => {
            switch (arguments.length){
                case 2:
                    this.redis.set(key,value,(error,result) => {if(!error){resolve(result);}});
                    break;
                case 3:
                    this.redis.set(key,value,arguments[2],(error,result) => {if(!error){resolve(result);}});
                    break;
                case 4:
                    this.redis.set(key,value,arguments[2],arguments[3],(error,result) => {if(!error){resolve(result);}});
                    break;
                case 5:
                    this.redis.set(key,value,arguments[2],arguments[3],arguments[4],(error,result) => {if(!error){resolve(result);}});
                    break;
            }
        });
    },
    expire:async function(key,expiresTime){
        return new Promise(resolve => {
            this.redis.expire(key,expiresTime,
                (error,result) => {
                    if(!error){
                        resolve(result);
                    }
                });
        });
    },
    end: function(){
        this.redis.end(true);
        return this;
    }
}

module.exports = myRedis;